import { getRole,getRoleSearchList } from '@/services';
import { Role,SearchRoleList } from '@/types';
import { Effect, Reducer } from 'umi';

export interface RoleModelState {
  roleList: Role[];
  SearchRoleList:SearchRoleList[]
}

export interface roleModelType {
  namespace: 'sysRole';
  state: RoleModelState;
  effects: {
    getRole: Effect;
    getRoleSearchList:Effect;
  };
  reducers: {
    save: Reducer<RoleModelState>;
  };
}

const ArticleModel: roleModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'sysRole',

  // 数据模型状态，相当于vuex的state
  state: {
    roleList: [],
    SearchRoleList:[]
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    // 总数据
    *getRole({ payload }, { call, put }) {
      let result = yield call(getRole, payload);
      if (result.records) {
        yield put({
          type: 'save',
          payload: {
            roleList: result.records,
          },
        });
      }
    },
    *getRoleSearchList({ payload }, { call, put }) {
      const result = yield call(getRoleSearchList,payload);
      localStorage.setItem('RoleSearchList',JSON.stringify(result.records));
      if (result) {
          yield put({
              type: "save",
              payload: {
                SearchRoleList: result.records,                       
              }
          })
      }
    },
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default ArticleModel;
